/**
 * Copyright 2012-2015 Niall Gallagher
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.cqengine.query.parser.sql.support;

import com.googlecode.cqengine.query.parser.common.ValueParser;

import java.lang.reflect.Method;

/**
 * Parses values using a static {@code valueOf()} method in the type's class.
 * <p/>
 * Created by npgall on 25/05/2015.
 */
public class FallbackValueParser extends ValueParser<Object> {

    final StringParser stringParser;

    public FallbackValueParser(StringParser stringParser) {
        this.stringParser = stringParser;
    }

    @Override
    protected Object parse(Class<?> valueType, String stringValue) {
        try {
            stringValue = stringParser.parse(String.class, stringValue);
            Method valueOf = valueType.getMethod("valueOf", String.class);
            return valueType.cast(valueOf.invoke(null, stringValue));
        }
        catch (Exception e) {
            throw new IllegalStateException("Failed to parse value using a valueOf() method in class '" + valueType.getName() + "': " + stringValue, e);
        }
    }
}
